package com.example.mq.common;

import java.io.*;

/**
 * 序列化与反序列化工具
 */
public class BinaryTool {
    public static byte[] toBytes(Object object) throws IOException {
        // 将对象序列化成字节数组
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                objectOutputStream.writeObject(object);
            }
            // 将二进制数据转成 byte[]
            return byteArrayOutputStream.toByteArray();
        }
    }

    public static Object fromBytes(byte[] data) throws IOException, ClassNotFoundException {
        // 将字节数组反序列化成对象
        Object object = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)) {
            try (ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
                // readObject 可以直接读取数据并进行反序列化
                object = objectInputStream.readObject();
            }
        }
        return object;
    }
}
